package pcap

import (
	"encoding/json"
	"fmt"
	"regexp"
)

// PrintStruct 打印结构体
func PrintStruct(i interface{}) {
	jsons, err := json.Marshal(i)
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Println(string(jsons))
}

// Struct2Json Struct转Json
func Struct2Json(i interface{}) string {
	jsons, err := json.Marshal(i)
	if err != nil {
		fmt.Println(err.Error())
	}
	return string(jsons)
}

var mailPattern = `
From: (.+?@.+?)\s
To: (.+?@.+?)\s
Message-ID: (.+?)
Subject: ([.\s\S]+?)\s
MIME-Version: (\d.\d)\s
Content-Type: (.+?)
Content-Transfer-Encoding: (.+?)
\s*?
([a-zA-Z0-9+=/\s]+)
`

type emailMatcher struct {
	re *regexp.Regexp
}

func newEmailMatcher() emailMatcher {
	em := emailMatcher{}
	em.re = regexp.MustCompile(mailPattern)
	return em
}

func (e *emailMatcher) match(s string) []string {
	result := e.re.FindStringSubmatch(s)
	if len(result) != 9 {
		return nil
	}

	return result
}

// 用于匹配HTTP相关的内容和信息
var pathPtn = `(?:GET|POST) ([\s\S]+?) HTTP\/\d.\d`
var hostPtn = `Host: ([^\s]+)\s*?`

// var contentEncodingPtn = `Content-Encoding: (.*?)\s` //deflate
var contentTypePtn = `Content-Type: (.*?)\s` // envelope/json
// var acceptEncodingPtn = `Accept-Encoding: (.*?)\s`   //gzip
// var contentLengthPtn = `Content-Length: (\d+?)\s`

var pathRe = regexp.MustCompile(pathPtn)
var hostRe = regexp.MustCompile(hostPtn)
var contentTypeRe = regexp.MustCompile(contentTypePtn)

// 用于临时处理、存放邮箱相关信息
type tmpMailInfo struct {
	name  string // 邮箱
	nFlag bool   // 下一个包传的是否为邮箱
	pFlag bool   // 下一个包传的是否为密码
	port  uint16 // 端口
	data  string // 存放所有的邮箱原始数据，用于过滤重复邮箱
}

var tmi = tmpMailInfo{
	data: "",
}

func (t *tmpMailInfo) clear() {
	t.nFlag = false
	t.pFlag = false
	t.name = ""
	t.port = 0
}
